觀察 index-Start.html 的 Javascrript 部分,這次相對第四天簡單多了,一樣每題都有限制要使用哪種 Array method 完成題目需求讓你順便學到新 Array method。
Date()
物件並改用Date.prototype.getFullYear()
const people = [
{ name: "Wes", year: 1988 },
{ name: "Kait", year: 1986 },
{ name: "Irv", year: 1970 },
{ name: "Lux", year: 2015 },
];
const nowYear = new Date().getFullYear();
Is at least one person 19 or older?(是否有人大於 19 歲)
這題使用到Array.prototype.some(),這個 Array method 是用來判斷陣列中的元素只要有任何一項符合判斷式
即會回傳 true,有點像 Array 版的Logical OR (||)
const isSomeAdult = people.some((person) => nowYear - person.year > 19);
console.log({ isSomeAdult });
is everyone 19 or older?
這題使用到Array.prototype.every(),這個 Array method 是用來判斷陣列中的所有元素都要符合判斷式
才會回傳 true,有點像 Array 版的Logical AND (&&)
const isAllAdult = people.every((person) => nowYear - person.year > 19);
console.log({ isAllAdult });
id
符合823423
的項目及 index,最後刪除它,我們先宣告變數targetID
來儲存這個會重複使用的 id 值const comments = [
{ text: "Love this!", id: 523423 },
{ text: "Super good", id: 823423 },
{ text: "You are the best", id: 2039842 },
{ text: "Ramen is my fav food ever", id: 123523 },
{ text: "Nice Nice Nice!", id: 542328 },
];
const targetID = 823423;
const result = comments.find((comment) => comment.id === targetID);
console.log(result);
const targetIndex = comments.findIndex((comment) => comment.id === targetID);
console.log({ targetIndex });
comments.splice(targetIndex, 1);
console.log(comments);